import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../modules/widgets/hint_dialog.dart';

extension PermissionUtil on Permission {
  requestPermission(
    BuildContext context,
    Function success, {
    String? title,
  }) async {
    if (await isGranted) {
      success.call();
    } else if (await request() == PermissionStatus.granted) {
      success.call();
    } else {
      final isPermanentlyDenied = await this.isPermanentlyDenied;
      HintDialog(
        content: title ?? '当前操作需要您同意权限',
        leftText: "手动开启",
        leftButtonFunction: (context) {
          Navigator.pop(context);
          openAppSettings();
        },
        rightText: '再试一次',
        rightButtonFunction: () {
          if (isPermanentlyDenied) return null;
          return (context) {
            Navigator.pop(context);
            requestPermission.call(context, success, title: title);
          };
        }(),
      ).show(context);
    }
  }
}
